package com.ifast.sys.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.domain.DictDO;
import com.ifast.common.domain.TreeNode;
import com.ifast.common.service.DictService;
import com.ifast.common.type.EnumErrorCode;
import com.ifast.common.utils.*;
import com.ifast.sys.domain.DeptDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.DeptService;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * 部门管理
 * </pre>
 * 
 * <small> 2018年3月23日 | Aron</small>
 * @author Administrator
 */
@Controller
@RequestMapping("/sys/dept")
public class DeptController extends AdminBaseController {
    private String prefix = "sys/dept";

    @Autowired
    private DeptService sysDeptService;

    @Autowired
    private DictService dictService;

    @GetMapping("/qyDept")
    @Log("进入部分页面")
    @RequiresPermissions("system:sysDept:sysDept")
    public String qyDept(Model model) {
        UserDO userDO = ShiroUtils.getSysUser();
        model.addAttribute("glyDept",Objects.requireNonNull(userDO).getDeptId());
        return prefix + "/qyDept";
    }

    @GetMapping("/glyDept")
    @Log("进入部门树形显示页面")
    @RequiresPermissions("system:sysDept:sysDept")
    public String glyDept() {
        return prefix + "/glyDept";
    }


    @GetMapping("/ptDept")
    @Log("进入部门树形显示页面")
    @RequiresPermissions("system:sysDept:sysDept")
    public String ptDept() {
        return prefix + "/ptDept";
    }

    @GetMapping("/commonDept")
    @Log("进入部分页面")
    @RequiresPermissions("system:sysDept:sysDept")
    public String ptDept(Model model,String deptId,String qylbId) {
        model.addAttribute("deptId", deptId);
        model.addAttribute("qylbId", qylbId);
        return prefix + "/commonDept";
    }


    @GetMapping("/xzDept")
    @Log("进入部分页面")
    public String xzDept() {
        return prefix + "/xzDept";
    }


    /**
     * 维护单位行业
     */
    @ResponseBody
    @GetMapping("/listDwhy")
    @Log("获取维护单位行业列表")
    @RequiresPermissions("system:sysDept:sysDept")
    public Result<Page<DeptDO>>  listDwhy(DeptDO deptDTO) {
        UserDO userDO = ShiroUtils.getSysUser();
        deptDTO.setId(Objects.requireNonNull(userDO).getDeptId());
        Page<DeptDO> page = sysDeptService.listPageDwhy(getPage(DeptDO.class),deptDTO);
        List<DeptDO> deptDoList = page.getRecords();
        if(CollectionUtil.isNotEmpty(deptDoList)){
            List<String> dIds = deptDoList.stream().map(DeptDO::getQylbId).collect(Collectors.toList());
            List<DictDO> dictDoList = this.dictService.selectBatchIds(dIds);
            Map<String,String> maps = dictDoList.stream().collect(Collectors.toMap(DictDO::getId,DictDO::getName));
            for (DeptDO deptDO : deptDoList) {
                deptDO.setQylbName(maps.getOrDefault(deptDO.getQylbId(), ""));
            }
        }
        return Result.ok(page);
    }


    @ResponseBody
    @GetMapping("/listDw")
    @Log("获取部门列表")
    @RequiresPermissions("system:sysDept:sysDept")
    public Result<Page<DeptDO>>  listDw(DeptDO deptDTO) {
        UserDO userDO = ShiroUtils.getSysUser();
        if(StrUtil.isBlank(deptDTO.getId())){
            deptDTO.setId(Objects.requireNonNull(userDO).getDeptId());
        }
        Page<DeptDO> page = sysDeptService.listPage(getPage(DeptDO.class),deptDTO);
        List<DeptDO> deptDoList = page.getRecords();
        if(CollectionUtil.isNotEmpty(deptDoList)){
           List<String> dIds = deptDoList.stream().map(DeptDO::getQylbId).collect(Collectors.toList());
           List<DictDO> dictDoList = this.dictService.selectBatchIds(dIds);
           Map<String,String> maps = dictDoList.stream().collect(Collectors.toMap(DictDO::getId,DictDO::getName));
            for (DeptDO deptDO : deptDoList) {
                deptDO.setQylbName(maps.getOrDefault(deptDO.getQylbId(), ""));
                DeptDO deptDoPz = this.sysDeptService.selectById(deptDO.getParentId());
                deptDO.setParentName(deptDoPz == null ? "" : deptDoPz.getName());
            }
        }
        return Result.ok(page);
    }


    @GetMapping("/add/{pId}")
    @Log("进入添加部门页面")
    @RequiresPermissions("system:sysDept:add")
    public String add(@PathVariable("pId") String pId, Model model) {
        model.addAttribute("pId", pId);
        model.addAttribute("pName", sysDeptService.selectById(pId).getName());
        return prefix + "/add";
    }

    @GetMapping("/addChild/{pId}")
    @Log("进入添加部门页面")
    @RequiresPermissions("system:sysDept:add")
    public String addChild(@PathVariable("pId") String pId, Model model) {
        model.addAttribute("pId", pId);
        model.addAttribute("pName", sysDeptService.selectById(pId).getName());
        return prefix + "/addChild";
    }


    @GetMapping("/edit/{deptId}")
    @RequiresPermissions("system:sysDept:edit")
    @Log("编辑部门")
    public String edit(@PathVariable("deptId") String deptId, Model model) {
        DeptDO sysDept = sysDeptService.selectById(deptId);
        model.addAttribute("sysDept", sysDept);
        DeptDO parDept = sysDeptService.selectById(sysDept.getParentId());
        model.addAttribute("parentDeptName", parDept.getName());
        return prefix + "/edit";
    }


    @GetMapping("/editChild/{deptId}")
    @RequiresPermissions("system:sysDept:edit")
    @Log("编辑部门")
    public String editChild(@PathVariable("deptId") String deptId, Model model) {
        DeptDO sysDept = sysDeptService.selectById(deptId);
        model.addAttribute("sysDept", sysDept);
        DeptDO parDept = sysDeptService.selectById(sysDept.getParentId());
        model.addAttribute("parentDeptName", parDept == null ? "" : parDept.getName());
        return prefix + "/editChild";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:sysDept:add")
    @Log("保存部门")
    public Result<String> save(DeptDO sysDept) {
        sysDept.setId(Const.uuid());
        try {
            sysDeptService.clInsertDept(sysDept);
        } catch (Exception e) {
            GjpLogger.error(e.toString(),e);
            return Result.fail("保存失败，可能单位级别大于7级或单位名称重复!");
        }
        return Result.ok(sysDept.getId());
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/saveChild")
    @RequiresPermissions("system:sysDept:add")
    @Log("保存部门")
    public Result<String> saveChild(DeptDO sysDept) {
        DeptDO deptDo =  this.sysDeptService.selectById(sysDept.getParentId());
        if(deptDo != null){
            DeptDO deptDoTwo = new DeptDO();
            BeanUtil.copyProperties(deptDo,deptDoTwo);
            deptDoTwo.setId(Const.uuid());
            deptDoTwo.setName(sysDept.getName());
            deptDoTwo.setOrderNum(sysDept.getOrderNum());
            deptDoTwo.setParentId(deptDo.getId());
            try {
                sysDeptService.clInsertDept(deptDoTwo);
            } catch (Exception e) {
                GjpLogger.error(e.toString(),e);
                return Result.fail("保存失败，可能单位级别大于7级或单位名称重复!");
            }
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:sysDept:edit")
    public Result<String> update(DeptDO sysDept) {
        sysDeptService.updateById(sysDept);
        return Result.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:sysDept:remove")
    @Log("删除部门")
    public Result<String> remove(String id) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("parentId", id);
        int size = sysDeptService.selectByMap(map).size();
        if (size > 0) {
            return Result.build(EnumErrorCode.deptUpdateErrorExistChilds.getCode(),
                    EnumErrorCode.deptUpdateErrorExistChilds.getMsg());
        }
        if (sysDeptService.checkDeptHasUser(id)) {
            sysDeptService.deleteById(id);
            return Result.ok();
        } else {
            return Result.build(EnumErrorCode.deptDeleteErrorExistUsers.getCode(),
                    EnumErrorCode.deptDeleteErrorExistUsers.getMsg());
        }
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:sysDept:batchRemove")
    @Log("删除部门")
    public Result<String> remove(@RequestParam("ids[]") String[] deptIds) {
        sysDeptService.deleteBatchIds(Arrays.asList(deptIds));
        return Result.ok();
    }

    /**
     * 初始化使用
     */
    @PostMapping("/zTree")
    @ResponseBody
    @Log("查询部门树形数据")
    public List<TreeNode> zTree(String id){
        if(StrUtil.isBlank(id)){
            id = Objects.requireNonNull(ShiroUtils.getSysUser()).getDeptId();
            List<DeptDO> listRoot = Lists.newArrayList();
            DeptDO deptDO = this.sysDeptService.selectById(id);
            listRoot.add(deptDO);
            return BuildZTree.buildDept(listRoot);
        }
       return sysDeptService.getDeptByAuth(id);
    }


    @PostMapping("/zTreeHangYe")
    @ResponseBody
    @Log("查询部门树形数据")
    public List<TreeNode> zTreeHangYe(){
        return sysDeptService.getDeptHanyeByAuth(Objects.requireNonNull(ShiroUtils.getSysUser()).getDeptId());
    }

    @GetMapping("/updateTree")
    @ResponseBody
    public void updateTree(){
        sysDeptService.updateTree();
    }



}
